using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.FormsManagement
{
    /// <summary>
    /// QuestionnairePreview shows how the questionnaire would look to the user
    /// </summary>
    public partial class QuestionnairePreview : BasePage
    {
        #region Constants

        private const string SelectedQuestionnaireIdKey = "SelectedQuestionnaireIdKey_4E0B5E3F-881A-4888-A3B2-FCFD63AE69E5";
        private const string SelectedQuestionnaireVersionIdKey = "SelectedQuestionnaireVersionIdKey_C2FD8E3D-AFF9-44aa-BE3A-8C6B6C9B0EF2";

        #endregion

        #region Instance Variables (private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Page Events

        /// <summary>
        /// Loads the questionnaire in the questionnaire viewer control
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            try
            {
                if (header.ModuleName == InsightUtilities.Constants.Modules.Admin)
                {
                    adminHumansSubNavigation.Visible = true;
                    coiSubNavigation.Visible = false;
                }
                else if (header.ModuleName == InsightUtilities.Constants.Modules.COI)
                {
                    adminHumansSubNavigation.Visible = false;
                    coiSubNavigation.Visible = true;
                    questionaireTitle.Visible = false;
                }

                breadCrumb.Add(" Forms Management",
                    Settings.GetKeyValue("SubNavigation.Admin.humansURL", ""),
                    Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));
                if (!IsPostBack && postbackGuard.IsValid)
                {
                    Hashtable incomingData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                    Hashtable questionnairesList = (Hashtable) cachePolicy.GetCachedObject(Keys.QuestionnaireObjectsKey);
                    Questionnaire questionnaire = (Questionnaire) questionnairesList[Convert.ToInt32(incomingData[Keys.QuestionnaireIdKey])];
                    questionaireTitle.Text = questionnaire.Name;
                    QuestionnaireVersion questionnaireVersion = questionnaire.GetQuestionnaireVersionById(Convert.ToInt32(incomingData[Keys.QuestionnaireVersionIdKey]));
                    questionnaireViewer.LoadQuestionnaire(questionnaireVersion, null);
                }
            }
            catch
            {
                annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
                annunciator.Message = "Failed to load the page.";
            }
            finally
            {
                if (coiSubNavigation.Visible)
                {
                    coiSubNavigation.SelectedLink = "Forms Management";
                    coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
                }
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization
        /// </summary>
        /// <param name="e">Arguments associated with the event.</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.breadCrumb.Navigate += new CommandEventHandler(OnNavigate);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Control Events

        /// <summary>
        /// Close the preview
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnClosePreviewClick(object sender, EventArgs e)
        {
            try
            {
                Response.Redirect(Settings.GetKeyValue("SubNavigation.Admin.Humans.FormEditorURL", "FormEditor.aspx"), false);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                adminSubNavigation.Reset();
                adminHumansSubNavigation.Reset();
                coiSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        #endregion
    }
}